package com.pi;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 执行打包
 */
public class PatchPlugin {


    private static Logger log = LoggerFactory.getLogger(PatchPlugin.class);



    /**
     * 拷贝补丁包
     *
     * @param data
     * @param newVersionPath
     * @param patchDir
     * @throws IOException
     */
    public static void exec(List<PatchFile> data, String newVersionPath, String patchDir, String patchBaseDir) throws IOException {

        if (null != data && !data.isEmpty()) {


            StringBuffer logInfo = new StringBuffer();
            StringBuffer fileDiff = new StringBuffer();
            SimpleDateFormat sdf = new SimpleDateFormat(
                    "创建时间 yyyy-MM-dd HH:mm:ss");

            logInfo.append(sdf.format(new Date())).append("\r\n");

            for (int i = 0; i < data.size(); i++) {
                PatchFile patchFile = data.get(i);

                fileDiff.append(patchFile.getFileStatus() == 1 ? "新增" : "修改")
                        .append("\t\t").append(patchFile.getPath()).append("\r\n");

                File newFile = FileUtil.getBaseFile(patchFile, newVersionPath, patchDir);

                boolean result = false;
                try {
                    FileUtils.copyFile(patchFile, newFile);
                    result = true;
                } catch (IOException e) {
                    e.printStackTrace();
                }

                logInfo.append("生成").append(result ? "成功" : "失败").append("\t")
                        .append(newFile.getAbsolutePath()).append("\r\n");

            }

            log.info(logInfo.toString());
            log.info(fileDiff.toString());
//            File logFile = new File(patchBaseDir, "patch.log");
//            FileUtil.createFileIfNotExists(logFile);
//
//            try (FileOutputStream logFos = new FileOutputStream(logFile)) {
//                IOUtils.write(logInfo.toString(), logFos);
//            }
//
//            File difFile = new File(patchBaseDir, "make.log");
//            FileUtil.createFileIfNotExists(difFile);
//
//            try (FileOutputStream fos = new FileOutputStream(difFile)) {
//                IOUtils.write(fileDiff.toString(), fos);
//            }
        }

    }
}
